package com.starbaba.oneUnion.view;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;

import com.base.common.database.BaseDao;
import com.base.common.exception.AppException;
import com.base.common.log.LogService;
import com.google.gson.JsonObject;
import com.opensymphony.xwork2.ModelDriven;
import com.starbaba.activityCommend.model.LoanProductChannelModel;
import com.starbaba.common.ResultJson;
import com.starbaba.controllog.aop.LogAble;
import com.starbaba.controllog.model.ControlLogCategory;
import com.starbaba.core.utils.PropertyParamMapBuilder;
import com.starbaba.core.utils.Struts2Utils;
import com.starbaba.core.utils.json.JsonUtils;
import com.starbaba.core.web.page.PageResponse;
import com.starbaba.core.web.struts2.BaseAction;
import com.starbaba.loanActivity.model.UserCommentModel;
import com.starbaba.loanActivity.service.LoanProductService;
import com.starbaba.model.dictionary.Constant;
import com.starbaba.oneUnion.model.FirstPartyModel;
import com.starbaba.oneUnion.model.OneUnionModel;

@SuppressWarnings({ "serial", "unused" })
public class OneUnionAction extends BaseAction implements ModelDriven<OneUnionModel> {

	@SuppressWarnings("deprecation")
	final static BaseDao dao = new BaseDao(Constant.POOL_LIFE);

	private OneUnionModel model;

	private LoanProductService service;

	private ArrayList<ControlLogCategory> logCategorysArrayList;

	@Autowired
	@Qualifier("loanProductServiceImpl")
	public void setService(LoanProductService service) {
		this.service = service;
	}

	@Override
	public OneUnionModel getModel() {
		if (model == null) {
			model = new OneUnionModel();
		}
		return model;
	}

	public String show() {
		List<LoanProductChannelModel> listtemp = getChannelList();
		paramsMap.put("modelList", listtemp);
		return SUCCESS;
	}

	/**
	 * 模板列表
	 * 
	 * @return
	 * @throws Exception
	 */
	public List<LoanProductChannelModel> getChannelList() {

		String sql = "select channel_code,channel_name from comm_product_channel";
		try {
			List<LoanProductChannelModel> list = dao.list(sql, LoanProductChannelModel.class, new Object[] {});

			return list;
		} catch (AppException e) {

			e.printStackTrace();
		}
		return null;
	}

	public void getFirstPatryList() throws AppException, ParseException {
		paramsMap = PropertyParamMapBuilder.buildFromHttpRequest(Struts2Utils.getRequest(), paramsMap);
		parsePageRequest();

		PageResponse pageResponse = new PageResponse<Object>();
		int start = pageRequest.getIDisplayStart();
		int length = pageRequest.getIDisplayLength();
		List<Object> params = new ArrayList<Object>();
		String channel = (String) paramsMap.get("channel");
		String cdate = (String) paramsMap.get("cdate");
		String prdid = (String) paramsMap.get("prdid");
		String pagefrom = (String) paramsMap.get("pagefrom");
		StringBuffer buffer = new StringBuffer();
		buffer.append("select count,a.channel channel,(case when name is not null then name else a.type end)as name ,cdate from (  ");
		buffer.append("select count(1) count, r.channel,type,DATE_FORMAT(r.ctime,'%Y-%m-%d') cdate  from loan_api_record r ");
		buffer.append("where first_union = 1 ");
		if (StringUtils.isNotEmpty(prdid)) {
			buffer.append("and product_id = ? ");
			params.add(prdid);
		}
		if (StringUtils.isNotEmpty(channel)) {
			buffer.append(" and  channel = ?  ");
			params.add(channel);
		}
		if (StringUtils.isNotEmpty(cdate)) {
			String cdate_after = getNextDay(cdate);
			buffer.append("and ctime >= ? AND ctime < ? ");
			params.add(cdate);
			params.add(cdate_after);
		}
		if (StringUtils.isNotEmpty(pagefrom)) {
			if (pagefrom.equals("0")) {
				buffer.append("and (page_from is null or page_from = 0)");
			} else {
				buffer.append("and page_from = ? ");
				params.add(pagefrom);
			}
		}
		buffer.append("group by r.type , r.channel) a ");
		buffer.append("LEFT JOIN loan_product_info p on  ");
		buffer.append("a.type = p.union_type ");
		buffer.append("order by count desc ");
		String sql = buffer.toString();
		List<FirstPartyModel> result = dao.list(sql, FirstPartyModel.class, params);
		pageResponse.setAaData(result);
		pageResponse.setSEcho(pageRequest.getSEcho());
		try {
			sendJsonMessage(JsonUtils.toJson(pageResponse, null, true, null, false));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private String getNextDay(String cdate) throws ParseException {
		Calendar calendar = Calendar.getInstance();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		calendar.setTime(sdf.parse(cdate));
		calendar.add(Calendar.DAY_OF_YEAR, 1);
		Date date = calendar.getTime();
		String cdate_after = sdf.format(date);
		return cdate_after;
	}

	public void getInfo() throws AppException, ParseException {

		paramsMap = PropertyParamMapBuilder.buildFromHttpRequest(Struts2Utils.getRequest(), paramsMap);
		parsePageRequest();

		PageResponse pageResponse = new PageResponse<Object>();
		int start = pageRequest.getIDisplayStart();
		int length = pageRequest.getIDisplayLength();

		String channel = (String) paramsMap.get("channel");
		String cdate = (String) paramsMap.get("cdate");
		String prdid = (String) paramsMap.get("prdid");
		String pagefrom = (String) paramsMap.get("pagefrom");
		String cdate_after = null;

		if (StringUtils.isNotEmpty(cdate)) {
			cdate_after = getNextDay(cdate);
		}
		StringBuffer buffer = new StringBuffer();
		List<Object> params = new ArrayList<Object>();
		buffer.append("select (case when fill_info_uv is not null then fill_info_uv else '0' end)as fill_info_uv , ");
		buffer.append("(case when union_uv is not null then union_uv else '0' end)as union_uv , ");
		buffer.append("(case when register_uv is not null then register_uv else '0' end)as register_uv , ");
		buffer.append("(case when app_register is not null then app_register else '0' end)as app_register , ");
		buffer.append("(case when r_success is not null then r_success else '0' end)as r_success,");
		buffer.append(" a.channel,'").append(cdate).append("' as cdate from ( ");
		buffer.append("select count(1) as fill_info_uv,channel from (select id,channel from onekey_union_channel_user_record where 1=1 ");
		if (StringUtils.isNotEmpty(prdid)) {
			buffer.append("and prdid = ? ");
			params.add(prdid);
		}
		if (StringUtils.isNotEmpty(pagefrom)) {
			buffer.append("and pagefrom = ? ");
			params.add(pagefrom);
		}

		if (StringUtils.isNotEmpty(cdate)) {
			buffer.append("and cdate = ? ");
			params.add(cdate);
		}
		if (StringUtils.isNotEmpty(channel)) {
			buffer.append(" and channel = ? ");
			params.add(channel);
		}
		buffer.append("group by userid ) temp group by channel) a left join( ");
		buffer.append("select count(1) as union_uv,channel from (select mobnum,channel from  ");
		buffer.append("loan_api_record r where 1=1 ");
		if (StringUtils.isNotEmpty(prdid)) {
			buffer.append("and r.product_id = ? ");
			params.add(prdid);
		}
		if (StringUtils.isNotEmpty(cdate)) {
			buffer.append("and ctime >= ? AND ctime < ? ");
			params.add(cdate);
			params.add(cdate_after);
		}
		if (StringUtils.isNotEmpty(channel)) {
			buffer.append(" and channel = ? ");
			params.add(channel);
		}
		buffer.append(" GROUP by mobnum)temp  group by channel) b on a.channel = b.channel left join ( ");
		buffer.append("select count(1)  as register_uv,channel from ( ");
		buffer.append("select r.phone,r.channel from comm_user c ,(select * from onekey_union_channel_user_record where 1=1 ");
		if (StringUtils.isNotEmpty(cdate)) {
			buffer.append("and cdate =? ");
			params.add(cdate);
		}
		buffer.append("group by userid) r where  r.phone = c.mobnum  ");
		if (StringUtils.isNotEmpty(prdid)) {
			buffer.append("and r.prdid = ? ");
			params.add(prdid);
		}
		if (StringUtils.isNotEmpty(cdate)) {
			buffer.append("and ctime >= ? AND ctime < ? ");
			params.add(cdate);
			params.add(cdate_after);
			buffer.append("and activedate = ? ");
			params.add(cdate);
		}
		if (StringUtils.isNotEmpty(channel)) {
			buffer.append(" and r.channel = ? ");
			params.add(channel);
		}
		buffer.append("GROUP by mobnum ");
		buffer.append(") temp group by channel) c on a.channel = c.channel left join ( ");
		buffer.append("select count(1)as app_register,channel from ( ");
		buffer.append("select r.phone,r.channel from comm_user c ,(select * from onekey_union_channel_user_record where 1=1 ");
		if (StringUtils.isNotEmpty(cdate)) {
			buffer.append("and cdate =? ");
			params.add(cdate);
		}
		buffer.append("group by userid) r where  r.phone = c.mobnum and c.phoneid is not null ");
		if (StringUtils.isNotEmpty(prdid)) {
			buffer.append("and r.prdid = ? ");
			params.add(prdid);
		}
		if (StringUtils.isNotEmpty(cdate)) {
			buffer.append("and ctime >= ? AND ctime < ? ");
			params.add(cdate);
			params.add(cdate_after);
			buffer.append("and activedate = ? ");
			params.add(cdate);
		}
		if (StringUtils.isNotEmpty(channel)) {
			buffer.append(" and r.channel = ? ");
			params.add(channel);
		}
		buffer.append(")temp group by channel) d on a.channel = d.channel left join ( ");
		buffer.append("select count(1) as r_success,channel from (select mobnum,channel from loan_api_record r where 1=1  ");
		if (StringUtils.isNotEmpty(prdid)) {
			buffer.append("and r.product_id = ? ");
			params.add(prdid);
		}
		if (StringUtils.isNotEmpty(cdate)) {
			buffer.append("and ctime >= ? AND ctime < ? ");
			params.add(cdate);
			params.add(cdate_after);
		}
		if (StringUtils.isNotEmpty(channel)) {
			buffer.append(" and channel = ? ");
			params.add(channel);
		}
		buffer.append("and first_union = 1  )temp group by channel) e on a.channel = e.channel ");
		String sql = buffer.toString();
		List<OneUnionModel> result = dao.list(sql, OneUnionModel.class, params);
		pageResponse.setAaData(result);
		pageResponse.setSEcho(pageRequest.getSEcho());
		try {
			sendJsonMessage(JsonUtils.toJson(pageResponse, null, true, null, false));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 新增/编辑产品
	 * 
	 * @throws ParseException
	 * @throws IOException
	 */
	public void saveActivity() throws ParseException, IOException {
	}

	public void deleteComment() {
		paramsMap = PropertyParamMapBuilder.buildFromHttpRequest(Struts2Utils.getRequest(), paramsMap);
		String commId = (String) paramsMap.get("commentId");
		String deleteSql = "DELETE FROM loan_user_comment WHERE id = ?";
		String selectSql = "SELECT * FROM loan_user_comment c WHERE c.id = ?";
		try {
			UserCommentModel comm = dao.get(selectSql, UserCommentModel.class, commId);
			String activityId = comm.getActivity_id() + "";

			dao.delete(deleteSql, new Object[] { commId });
		} catch (AppException e) {
			e.printStackTrace();
		}
	}

	@LogAble(operate = LogAble.OPERATE_MODIFY)
	public void sortTab() {
		paramsMap = PropertyParamMapBuilder.buildFromHttpRequest(Struts2Utils.getRequest(), paramsMap);
		String prdidListStr = (String) paramsMap.get("prdSortList");
		String[] prdidList = prdidListStr.split("#");
		parsePageRequest();
		try {
			String sql = "update loan_product_info c set c.position = ? where c.id = ?";
			for (int index = 0; index < prdidList.length; ++index) {
				Long id = Long.parseLong(prdidList[index]);
				dao.update(sql, index, id);
			}
			responseSuccess();
		} catch (Exception e) {
			e.printStackTrace();
			responseError(e);
		}
	}

	/**
	 * 
	 *
	 * @Title responseSuccess
	 * @Description <p>
	 *              返回错误信息
	 *              </p>
	 *              　　　　　
	 * @author zhengjunjie
	 * @dateTime 2015年10月16日 下午2:26:53
	 *
	 */
	private void responseError(Exception error) {
		StringWriter writer = new StringWriter();
		error.printStackTrace(new PrintWriter(writer, true));
		ResultJson resultJson = new ResultJson(-2, 0, writer.toString());
		JsonObject result = new JsonObject();
		result.add("result", resultJson.toJSON());
		try {
			sendJsonMessage(result.toString());
		} catch (Exception e) {
			LogService.error(e);
		}
	}

	private void loadLogCategory(String id, String name) {
		logCategorysArrayList.clear();
		ControlLogCategory logCategory = new ControlLogCategory();
		logCategory.setId(id);
		logCategory.setName(name);
		logCategorysArrayList.add(logCategory);
	}

	@Override
	public ArrayList<ControlLogCategory> getProduct() {
		return logCategorysArrayList;
	}

	private void responseSuccess() {
		JsonObject result = new JsonObject();
		result.add("result", new ResultJson().toJSON());
		try {
			sendJsonMessage(result.toString());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}